/*
 *  Copyright 2011 yura.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.opu.db_vdumper.ui.component.area;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Point;
import org.opu.db_vdumper.ui.component.AbsoluteLayout;
import org.opu.db_vdumper.ui.component.PDimension;
import org.opu.db_vdumper.ui.component.PreferredLocation;
import org.opu.db_vdumper.ui.component.tabel.views.ArrowView;

/**
 *  Independently determine the location of the elements,
 * so that they do not intersect
 * @author Potochnak Yana
 */
public class SmartLayout extends AbsoluteLayout {
    public static int __Killme = 10;

    /**
     *  Independently determine the location of the elements. and put it to
     * @param name the component name
     * @param comp the component to be added
     */
    @Override
    public void addLayoutComponent(String name, Component comp) {
        doMarkingAndAdd(comp);
    }
    
    @Override
    public void addLayoutComponent(Component comp, Object constr) {
        doMarkingAndAdd(comp);
    }

    @Override
    public void invalidateLayout(Container target) {
        for (Component c : target.getComponents()) {
            Point cl = c.getLocation();
            Dimension cs = c.getPreferredSize();
            PDimension d = constraints.get(c);
            if (d != null){
                if (c instanceof ArrowView) {
                    Point sc = ((ArrowView) c).getPreferredLocation();
                    d.setX(sc.x);
                    d.setY(sc.y);
                } else {
                    if ((cl.getX() != d.getX() || cl.getY() != d.getY())){//chek only position
                        d.setX(cl.x);
                        d.setY(cl.y);
                    }
                }
            }
        }
    }

    /**
     *  Independently determine the location of the elements. and put it to
     * @param comp the component to be added
     */
    protected void doMarkingAndAdd(Component comp) {
        PDimension s;
        if (comp instanceof PreferredLocation){
            Point p = ((PreferredLocation) comp).getPreferredLocation();
            s = new PDimension(p.x, p.y);
        } else {
            s = new PDimension(__Killme, __Killme);
            __Killme += 100;
            comp.setLocation(s.getX(), s.getY());
        }
        super.addLayoutComponent(comp, s);
    }

}
